<template>
  <!-- <van-icon color="#777" name="good-job-o" /> -->
  <van-icon
    :name="value == 1 ? 'good-job' : 'good-job-o'"
    :class="{ liked: value == 1 }"
    :loading="loading"
    @click="onCollect"
  />
</template>
<script>
import { addLike, deleteLike } from "@/api/article.js";

export default {
  name: "LikeArticle",
  props: {
    value: {
      type: Number,
      required: true,
    },
    articleId: {
      type: [Number, String, Object],
      required: true,
    },
  },
  data() {
    return {
      loading: false,
    };
  },
  methods: {
    async onCollect() {
      this.loading = true;
      try {
        let status = -1; // 每次都会初始化状态;
        if (this.value == 1) {
          //如果已经点赞==>执行取消点赞
          await deleteLike(this.articleId); // 等待
          // 执行之后 this.value为-1 status也是-1;
        } else {
          //没有点赞 则 执行点赞
          // 点赞后 this.value=1; 那么 status也是还是-1  那么 需要改变status的值为1;
          // status和this.value状态始终一致;
          // 那为什么不直接使用this.value呢? 因为状态更新是异步的,执行顺序不同;
          // 所有要派生出一种代替状态;
          await addLike(this.articleId); //
          status = 1; //取消点赞变成1
        }

        this.$emit("input", status);
        this.$toast.success(status == 1 ? "点赞成功" : "取消点赞");
      } catch (err) {
        this.$toast.fail("操作失败,请重试!");
      }
      this.loading = false;
    },
  },
};
</script>

<style scoped lang="less"></style>
